import { defineConfig,loadEnv} from 'vite'
import vue from '@vitejs/plugin-vue'
import path from "path"
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
// https://vite.dev/config/
export default defineConfig(({mode})=>{
  const env=loadEnv(mode,process.cwd(),'')
  return {
    base: '/', // 这里更改打包相对绝对路径
    minify: true, // 是否压缩代码
    sourceMap: false, // 是否生成sourceMap
    resolve:{
      alias:{
        '@': path.resolve(__dirname, 'src'),
      }
    },
    css: {
      // css预处理器
      preprocessorOptions: { // 添加此配置
        scss: {
          additionalData: `@use "@/assets/style/element.scss" as *; `,
        }
      },
    },
    plugins: [
      vue(),
      Components({
        resolvers: [
          // 1、配置ElementPlus采用sass样式配色系统
          ElementPlusResolver({ importStyle: 'sass' }),
        ],
      }),
    ],
    build: {
      outDir: 'dist',
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules')[1].split('/.pnpm')[1].split('/@')[1]
            }
            // 如果没有匹配到任何条件，则返回undefined，让Rollup使用默认的分包策略
            return null;
          },
          entryFileNames: 'static/js/[name]-[hash].js',
          chunkFileNames: 'static/js/[name]-[hash].js',
          assetFileNames(assetInfo){
            if(assetInfo.name.endsWith('.css')){
              return `static/css/[name]-[hash].css`
            }
            let extname=['png', 'jpg', 'jpeg', 'svg', 'gif', 'webp', 'ico', 'avif']
            if(extname.some(ext=>assetInfo.name.endsWith(ext))){
              return `static/images/[name]-[hash][extname]`
            }
            return `static/css/[name]-[hash][extname]`
          },
        },
      },
      assetsInlineLimit: 0, // 默认是4kb，这里修改为0，不进行图片转base64，大于4kb的图片不转base64
      modulePreload:{
        strategy:'self',
      }
    },
    server: { 
      port:8089, // 服务端口
      open: true, // 是否自动打开浏览器
      https: false, // 是否开启https
      host:'0.0.0.0',
      proxy: {
        '/api': {
          target: env.VITE_API_URL, // 代理地址
          changeOrigin: true,
          // rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    }
  }
})
